package com.yicong.taxi.api.observers;

import android.text.TextUtils;

import com.yicong.taxi.R;
import com.yicong.taxi.api.ApiCode;
import com.yicong.taxi.api.entry.ApiResult;
import com.yicong.taxi.config.MyApp;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * 基础返回信息
 * 返回 实体类型
 */

public abstract class BaseObserver<T> implements io.reactivex.Observer<ApiResult<T>> {
  public BaseObserver() {
    onStart();
  }
  @Override public void onSubscribe(@NonNull Disposable d) {

  }
  @Override public void onNext(@NonNull ApiResult<T> tApiResult) {
    if (tApiResult.getReturnCode().equals(ApiCode.SUCCESS_CODE)) {
      if (null != tApiResult.getReturnMap()) {
        onSuccess(tApiResult.getReturnMap());
      } else {
        onSuccess(tApiResult.getData());
      }
    } else {
      onFail(tApiResult.getReturnCode(), tApiResult.getReturnMessage());
    }
    onFinish();
  }
  @Override public void onError(@NonNull Throwable e) {
    if (e instanceof HttpException) {
      onException(MyApp.getInstance().getResources().getString(R.string.error_message));
    } else if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
      onException(MyApp.getInstance().getResources().getString(R.string.error_message));
    } else if (e instanceof JSONException || e instanceof ParseException) {

    } else if (e instanceof UnknownHostException) {
      onException(MyApp.getInstance().getResources().getString(R.string.error_message));
    } else {
      if (!TextUtils.isEmpty(e.getMessage())) {
        onException(e.getMessage());
      } else {
        onException(MyApp.getInstance().getResources().getString(R.string.error_message));
      }
    }
    onFinish();
  }
  @Override public void onComplete() {
    onFinish();
  }
  // 开始
  public abstract void onStart();
  // 请求成功
  public abstract void onSuccess(T t);
  // 请求成功 + 但是获取数据失败 （如：密码错误、身份失效）
  public abstract void onFail(String code, String msg);
  // 请求异常
  public abstract void onException(String msg);
  // 请求完成
  public abstract void onFinish();
}
